package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"golang.org/x/xerrors"
	"sync"
)

type ginHandlerFunc = gin.HandlerFunc

type stCustRouter struct {
	method         string
	registeredPath string
	handlersFn     []ginHandlerFunc
}

var (
	registerMutex = new(sync.Mutex)
	routerFuncs   = make(map[string]*stCustRouter)
)

// RegisterRouterFn 注册api路由
func RegisterRouterFn(pfunc *stCustRouter) error {
	if pfunc != nil {
		registerMutex.Lock()
		defer registerMutex.Unlock()
		_, ok := routerFuncs[pfunc.method+pfunc.registeredPath]
		if ok {
			return xerrors.New(fmt.Sprintf("funcs %s[%s] is already exists!", pfunc.registeredPath, pfunc.method))
		} else {
			routerFuncs[pfunc.method+pfunc.registeredPath] = pfunc
			return nil
		}
	} else {
		return xerrors.New("funcs is nil!")
	}
}

func loadAllApiFuncs(pf *gin.Engine) error {
	if pf == nil {
		return xerrors.New("gin.Engine is nil!")
	}
	for _, fv := range routerFuncs {
		// 记录一下需要多授权
		if len(fv.handlersFn) > 1 {
			funcRequired = append(funcRequired, fv.method+":"+fv.registeredPath)
		}
		//apis 授权控制
		pf.Handle(fv.method, fv.registeredPath, fv.handlersFn...)
	}
	log.Info("funcRequired count:", len(funcRequired))
	return nil
}
